import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/banner_for_home_entity.dart';
import 'package:taonile/routers/routers.dart';
import 'package:taonile/utils/common_utils.dart';
import 'package:taonile/views/dialog_manager.dart';

import '../entity/announcement_list_entity.dart';
import '../entity/goods_area_category_entity.dart';
import '../entity/goods_source_list_entity.dart';
import '../entity/jingang_for_home_entity.dart';
import '../entity/product_entity.dart';
import '../http/api.dart';
import '../utils/string_utils.dart';
import '../views/home_index_top_layout.dart';
import '../views/mall_home_module.dart';
import '../views/marquee_widget.dart';
import '../views/store_home_module.dart';

class StoreHot extends StatefulWidget {
  const StoreHot({Key? key}) : super(key: key);

  @override
  State<StoreHot> createState() => _StoreHotState();
}

class _StoreHotState extends State<StoreHot> {
  //推荐商品
  List<ProductData> datas = [];
  var page = 1;

  //轮播
  List<BannerForHomeData> banners = [];
  bool isLoopBanner = false;

  var tabNames = [
    '全部',
    '美食',
    '酒店住宿',
    '休闲玩乐',
    '美容美发',
  ];
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    getBannerList();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getData() async {
    await getProducts();
  }

  getBannerList() async {
    dynamic result = await Api.bannerForHome({});
    BannerForHomeEntity entity = BannerForHomeEntity.fromJson(result);
    setState(() {
      banners.clear();
      banners.addAll(entity.data);
      Future.delayed(const Duration(milliseconds: 1500), () {
        setState(() {
          isLoopBanner = true;
        });
      });
    });
  }

  getProducts() async {
    dynamic result = await Api.goodsList({'page': page.toString(), 'size': '20'});
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  var tags = ['休闲、足浴', '2000人关注'];

  getSearchGuess(int index) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: StringUtils.getStringWidth(tags[index], 19.sp) + 15,
        height: 30.w,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(20.w),
          border: Border.all(color: Config.colorMain, width: 1.w),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              tags[index],
              style: TextStyle(color: Config.colorMain, fontSize: 18.sp),
            ),
          ],
        ),
      ),
    );
  }

  //返回商品列表item
  getListItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.storeDetail, params: {'storeId': datas[index].id});
      },
      child: Container(
        width: double.infinity,
        height: 175.w,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        padding: EdgeInsets.all(15.w),
        margin: EdgeInsets.only(bottom: 20.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.all(
                Radius.circular(12.w),
              ),
              child: CachedNetworkImage(
                imageUrl: datas[index].mainImg,
                fit: BoxFit.fill,
                width: 120.w,
                height: 120.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: 120.w,
                    height: 120.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
            Container(
              padding: EdgeInsets.only(left: 15.w),
              // decoration: const BoxDecoration(color: Config.),
              width: 560.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '雅诗兰黛官方旗舰店',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText1, fontSize: 26.sp),
                      ),
                      Text(
                        '09:00-22:00',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                      ),
                    ],
                  ),
                  Padding(padding: EdgeInsets.only(top: 16.w)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Wrap(
                        spacing: 15.w,
                        runSpacing: 15.w,
                        children: List.generate(tags.length, (index) => getSearchGuess(index)),
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.location_on_outlined,
                            size: 25.w,
                            color: Config.colorText1,
                          ),
                          Text(
                            '500m',
                            softWrap: false,
                            style: TextStyle(color: Config.colorText1, fontSize: 23.sp),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Padding(padding: EdgeInsets.only(top: 16.w)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '周一至周五可消费',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                      ),
                      Text(
                        '999人已消费',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  //返回菜单item
  getMenuItem(int position) {
    return InkWell(
      onTap: () {
        setState(() {
          _currentIndex = position;
        });
      },
      child: Container(
        width: StringUtils.getStringWidth(tabNames[position], 26.sp) + 60.w,
        decoration: BoxDecoration(color: Colors.transparent),
        padding: EdgeInsets.fromLTRB(0.w, 0, 0.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _currentIndex == position
                ? Text(
                    tabNames[position],
                    style: TextStyle(color: (Config.colorMain), fontSize: 26.sp),
                  )
                : Text(
                    tabNames[position],
                    style: TextStyle(color: (Config.colorText1), fontSize: 26.sp),
                  ),
            Opacity(
              opacity: _currentIndex == position ? 1 : 0,
              child: Container(
                width: 60.w,
                margin: EdgeInsets.only(top: 5.w),
                child: Divider(
                  color: Config.colorMain,
                  height: 3.w,
                  thickness: 3.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('热门推荐'),
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(0),
        width: double.infinity,
        decoration: const BoxDecoration(color: Config.colorBg2),
        height: double.infinity,
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.only(top: 0.w),
              child: EasyRefresh.builder(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  page = 1;
                  await getProducts();
                },
                onLoad: () async {
                  await getProducts();
                },
                childBuilder: (context, physics) {
                  return ListView(
                    scrollDirection: Axis.vertical,
                    // controller: controller,
                    physics: physics,
                    children: [
                      Container(
                        //轮播
                        padding: EdgeInsets.only(left: 25.w, right: 25.w, top: 25.w),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10.w),
                          color: Config.colorWhite,
                        ),
                        height: 306.w,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(10.w),
                          child: Swiper(
                            itemBuilder: (BuildContext context, int index) {
                              return CachedNetworkImage(
                                imageUrl: banners[index].imgPath,
                                fit: BoxFit.fill,
                                errorWidget: (context, url, error) {
                                  return Image.asset(
                                    'assets/images/bg_default_400.png',
                                    width: 700.w,
                                    height: 306.w,
                                    fit: BoxFit.fill,
                                  );
                                },
                              );
                            },
                            onTap: (index) {
                              // Routes.navigateTo(context, Routes.webView, params: {
                              //   'pageTitle': banners[index].id,
                              //   'webUrl': banners[index].link
                              // });
                            },
                            autoplayDelay: 4000,
                            autoplay: isLoopBanner,
                            loop: isLoopBanner,
                            layout: SwiperLayout.DEFAULT,
                            itemCount: banners.length,

                            // viewportFraction: 0.7,
                            // scale: 0.8,
                            pagination: SwiperPagination(
                              builder: DotSwiperPaginationBuilder(
                                  // size: Size(20.w, 4.w),
                                  // activeSize: Size(20.w, 4.w),
                                  size: 15.w,
                                  activeSize: 15.w,
                                  activeColor: Config.colorMain,
                                  color: Config.colorWhite),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        decoration: BoxDecoration(color: Config.colorWhite),
                        width: double.infinity,
                        height: 80.w,
                        child: ListView.builder(
                          itemCount: tabNames.length,
                          padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                          shrinkWrap: true,
                          scrollDirection: Axis.horizontal,
                          physics: const BouncingScrollPhysics(),
                          itemBuilder: (BuildContext context, int index) {
                            return getMenuItem(index);
                          },
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.only(left: 25.w, right: 25.w),
                        decoration: const BoxDecoration(color: Colors.white),
                        margin: EdgeInsets.only(top: 1.w),
                        height: 70.w,
                        child: InkWell(
                          onTap: () {
                            var datas = [
                              '综合排序',
                              '距离优先',
                            ];

                            DialogManager.showBottomMenu(context, datas, (index) {
                              LogUtil.v(index, tag: '选中的菜单下表');
                            });
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text(
                                '综合排序',
                                style: TextStyle(color: Config.colorText1, fontSize: 26.sp),
                              ),
                              Icon(
                                Icons.arrow_drop_down_sharp,
                                size: 26.w,
                                color: Config.colorText1,
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(20.w, 25.w, 20.w, 20.w),
                        width: double.infinity,
                        decoration: const BoxDecoration(color: Colors.transparent),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              width: double.infinity,
                              child: ListView.builder(
                                padding: EdgeInsets.symmetric(horizontal: 0.w),
                                itemCount: datas.length,
                                shrinkWrap: true,
                                scrollDirection: Axis.vertical,
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (BuildContext context, int index) {
                                  return getListItem(index);
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
